<template>
  <div class="search-box">
    <!-- 搜索页面 -->
    <form
      action="/"
      class="search-input"
    >
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3396fc"
        @search="onSearch"
        @cancel="$router.go(-1)"
        @focus="isShowSearchResult=false"
      />
    </form>
    <!-- 搜索结果  先判断搜索结果 这样三个才能融为一体-->
    <search-result
      :value='searchText'
      v-if="isShowSearchResult"
    ></search-result>
    <!-- 搜索历史   没有搜索内容的时候  显示搜索历史-->
    <search-history
      :history="history"
      v-else-if="!searchText"
      @search='onSearch'
    ></search-history>
    <!-- 搜索建议  有搜索内容 显示搜索简易-->
    <search-suggest
      :value='searchText'
      v-else
      @search='onSearch'
    ></search-suggest>

  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggest from './components/search-suggest'
import { setItem, getItem } from '@/utils/storage.js'
const HMTT_HISTORY = 'hmtt_history'
export default {
  name: 'search',
  data () {
    return {
      // 输入框双向绑定变量
      searchText: '',
      // 是否显示搜索结果
      isShowSearchResult: false,
      // 搜索结果历史数组
      history: getItem(HMTT_HISTORY) || []
    }
  },
  methods: {
    // 触发搜索处理方法
    onSearch (val) {
      // 将子组件传过来的值 赋值给  searchText
      // 把搜索关键词追加到 搜索历史数组的最前面
      this.history.unshift(val)
      // 利用set集合进行 数据去重  Set集合返回伪数组 所以要展开
      this.history = [...new Set(this.history)]
      this.searchText = val
      // 显示 搜索结果组件
      this.isShowSearchResult = true
    }
  },
  computed: {},
  watch: {
    history (nval) {
      setItem(HMTT_HISTORY, nval)
    }
  },
  filters: {},
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggest
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.search-box {
  // 右侧取消按钮样式
  .van-search__action {
    color: #fff;
  }
  .search-input {
    position: sticky;
    top: 0;
    z-index: 2;
  }
}
</style>
